<template>
  <el-card shadow="hover">
    <el-form label-width="100px" :model="model" :rules="rules" ref="formRef">
      <el-row :gutter="10">
        <el-col
          v-for="formItem in schema"
          :key="formItem.key"
          :span="formItem.colSpan || 24"
        >
          <el-form-item :prop="formItem.model" :label="formItem.label">
            <el-input
              v-if="formItem.type === 'input'"
              v-bind="formItem.props"
              v-model="model[formItem.model]"
            ></el-input>

            <el-select
              v-else-if="formItem.type === 'select'"
              v-bind="formItem.props"
              v-model="model[formItem.model]"
            >
              <el-option
                v-for="option in formItem.selectOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              ></el-option>
            </el-select>

            <el-upload
              v-else-if="formItem.type === 'upload'"
              v-model:file-list="model[formItem.model]"
              list-type="picture-card"
              v-bind="formItem.props"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>

              <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500KB.
                </div>
              </template>

              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-upload>

            <slot
              v-else-if="formItem.type === 'slot' && formItem.slot === 'btns'"
              :validate="validate"
              :name="formItem.slot"
            />
            <slot v-else-if="formItem.type === 'slot'" :name="formItem.slot" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
defineOptions({
  name: "SchemaForm",
});

defineProps<{
  schema: any;
  model: any;
  rules: any;
}>();

import { ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
// 图片上传功能
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const formRef = ref();

const validate = async (cb: any) => {
  await formRef.value.validate();
  cb();
};
</script>

<style scoped lang="scss"></style>
